<?php

namespace app\index\controller;

use app\model\Trademark;
use app\model\TrademarkOrder;
use think\exception\ValidateException;
use app\model\Cart;
use app\model\Order;
use app\model\Member;
use app\model\Config;
use app\model\OrderStatus;
use app\model\OrderHistory;
use app\model\OrderGoods;
use app\model\Goods;
use app\model\Paymethod;
use app\model\Users;
use app\model\OrderStaff;
use app\model\Address;
use app\model\Category;
use app\model\TransportExtend;
use app\model\Message;
use app\model\Technical;
use app\model\Area;
use app\model\RegisterField;
use app\model\Store;
use app\model\Operatingcity;
use app\model\Incomelog;
use app\model\Geocoder;
use app\model\OrderImage;
use app\model\OrderAddress;

class OrderController extends Base
{

    public function list()
    {
        $uuid        = $this->getuuid();
        $uid         = UID();
        $weid        = weid();
        $status      = input('post.status');
        $admin       = input('post.admin');
        $technical   = input('post.technical');
        $publicorder = input('post.publicorder');
        $store       = input('post.store');
        $ptype       = input('post.ptype');
        $is_times    = input('post.is_times');
        if (empty($ptype)) {
            $ptype = 1;
        }

        $query = Order::where(['weid' => $weid, 'ptype' => $ptype]);
        $query->with(['paymethod']);

        $Membermob = new Member;
        $Member    = $Membermob->getUserByWechat();

        if ($admin == 1) {
        } elseif ($store == 1) {
            $data = Store::where(['uid' => UID()])->find();
            if ($data) {
                $data = $data->toArray();
                $query->where('sid', $data['id']);
            }
        } elseif ($technical == 1) {

            if (!empty($uuid) && !empty($uid)) {
                OrderStaff::where('uid', $uid)->update(['uuid' => $uuid]);
            }

            $withJoin = [
                'staff' => ['order_id', 'uuid', 'title', 'endTime', 'beginTime'],
            ];
            $query->withJoin($withJoin, 'left');
            $query->where(['staff.uuid' => $uuid]);
        } elseif ($publicorder == 1) {
            return $this->publicorder();
        } else {
            $query->where(['uid' => $Member['id']]);
        }

        if (!empty($is_times)) {
            $query->where('is_times', $is_times);
        }

        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        $orderList = $query->order('id desc')->select()->toArray();

        //var_dump($query->getLastsql());

        $orderList = Order::setOrderList($orderList);

        $data["orderList"] = $orderList;
        //$data["amountLogistics"] = $amountLogistics;
        $data["isNeedLogistics"] = 1;
        $data['is_agent']        = $Member['is_agent'];

        return $this->json(['data' => $data]);
    }

    public function myorder()
    {
        $weid     = weid();
        $status   = input('post.status');
        $ptype    = input('post.ptype');
        $is_times = input('post.is_times');
        if (empty($ptype)) {
            $ptype = 1;
        }

        $query = Order::where(['weid' => $weid, 'ptype' => $ptype]);
        $query->with(['paymethod']);

        $Membermob = new Member;
        $Member    = $Membermob->getUserByWechat();

        $query->where(['uid' => $Member['id']]);


        if (!empty($is_times)) {
            $query->where('is_times', $is_times);
        }

        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();
        //var_dump($query->getLastsql());
        $res['data']  = Order::setOrderList($res['data']);
        $data['data'] = $res;

        return $this->json($data);
    }

    public function technicalorder()
    {
        $uuid   = $this->getuuid();
        $uid    = UID();
        $weid   = weid();
        $status = input('post.status');
        $ptype  = input('post.ptype');
        if (empty($ptype)) {
            $ptype = 2;
        }
        $query = Order::where(['weid' => $weid, 'ptype' => $ptype]);
        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        if (!empty($uuid) && !empty($uid)) {
            OrderStaff::where('uid', $uid)->update(['uuid' => $uuid]);
        }
        $withJoin = [
            'staff' => ['order_id', 'uuid', 'title', 'endTime', 'beginTime'],
        ];
        $query->withJoin($withJoin, 'left');
        $query->where(['staff.uuid' => $uuid]);

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();

        $res['data']  = Order::setOrderList($res['data']);
        $data['data'] = $res;

        return $this->json($data);
    }

    public function storeorder()
    {
        $weid   = weid();
        $status = input('post.status');
        $ptype  = input('post.ptype');

        if (empty($ptype)) {
            $ptype = 2;
        }
        $query = Order::where(['weid' => $weid, 'ptype' => $ptype]);
        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        $uuid      = $this->getuuid();
        $Storedata = Store::where(['uuid' => $uuid])->find();
        if ($Storedata) {
            $Storedata = $Storedata->toArray();
            $query->where('sid', $Storedata['id']);
        }

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();


        $res['data']  = Order::setOrderList($res['data']);
        $data['data'] = $res;

        return $this->json($data);
    }

    public function operatingcityorder()
    {
        $weid   = weid();
        $status = input('post.status');
        $ptype  = input('post.ptype');

        if (empty($ptype)) {
            $ptype = 2;
        }
        $query = Order::where(['weid' => $weid, 'ptype' => $ptype]);
        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        $uuid = $this->getuuid();

        $Operatingcitydata = Operatingcity::where(['uuid' => $uuid])->find();

        if ($Operatingcitydata) {
            $Operatingcitydata = $Operatingcitydata->toArray();

            if ($Operatingcitydata['areatype'] == 2) {
                $query->where('shipping_district_name_two', $Operatingcitydata['district_name']);
            } elseif ($Operatingcitydata['areatype'] == 1) {
                $query->where('shipping_city_name_two', $Operatingcitydata['city_name']);
            }
        }

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();


        $res['data']  = Order::setOrderList($res['data']);
        $data['data'] = $res;

        return $this->json($data);
    }

    public function adminorder()
    {

        $weid   = weid();
        $status = input('post.status');
        $ptype  = input('post.ptype');

        if (empty($ptype)) {
            $ptype = 2;
        }
        $query = Order::where(['weid' => $weid, 'ptype' => $ptype]);
        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();


        $res['data']  = Order::setOrderList($res['data']);
        $data['data'] = $res;

        return $this->json($data);
    }

    public function teamorder()
    {

        $weid   = weid();
        $status = input('post.status');
        $ptype  = input('post.ptype');

        $Membermob = new Member;
        $Member    = $Membermob->getUserByWechat();

        $where['weid'] = $weid;
        $where['uid']  = $Member['id'];

        $orderids = Incomelog::where($where)->column('order_id');

        $query = Order::where(['weid' => $weid]);

        if (!empty($ptype)) {
            $query->where('ptype', $ptype);
        }

        if (!empty($status)) {
            $query->where('order_status_id', $status);
        }

        $query->where('id', 'in', $orderids);
        //$uidlist = Member::getDepart($Member['id']);

        //$query->where(['uid' => $uidlist]);

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();


        $res['data']  = Order::setOrderList($res['data']);
        $data['data'] = $res;

        return $this->json($data);
    }

    public function publicorder()
    {
        $identity = input('post.identity');

        $from['longitude'] = input('post.longitude');
        $from['latitude']  = input('post.latitude');

        $weid  = weid();
        $ptype = input('post.ptype');
        if (empty($ptype)) {
            $ptype = 2;
        }
        $query = Order::where(['weid' => $weid, 'ptype' => $ptype]);
        $uuid  = $this->getuuid();

//        if ($identity == 'technical') {
//
//            $Technicaldata = Technical::where('uuid', $uuid)->find();
//            if (!empty($Technicaldata)) {
//                $cityName =  $Technicaldata->city_name;
//
//                $query->where(['sid' => (int) $Technicaldata->sid]);
//            }
//
//            if (!empty($cityName)) {
//                $query->where(['shipping_city_name_two' => $cityName]);
//            } else {
//                $query->where(['shipping_city_name' => '-1']);
//            }
//        }

        if ($identity == 'store') {
            $info = Store::where('uuid', $uuid)->find();
            if ($info) {
                $query = $query->where(['shipping_city_name_two' => $info['city_name']]);
            }
        } else {
            if ($identity == 'technical') {
                $info = Technical::where('uuid', $uuid)->find();
                if ($info) {
                    $query = $query->where(['shipping_city_name_two' => $info['city_name']]);
                }
            }
        }


        $query = $query->where(['order_status_id' => 2]);

        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();
        //var_dump($query->getLastsql());

        $res['data'] = Order::setOrderList($res['data']);
        if ($from['longitude'] && $from['latitude']) {
            foreach ($res['data'] as &$vo) {

                $addressdata = OrderAddress::where(['order_id' => $vo['id'], 'ptype' => 1])->find();

                if (empty($addressdata)) {
                    $addressdata = Address::find($vo['address_id']);
                }

                if (!empty($addressdata)) {
                    $addressdata      = $addressdata->toArray();
                    $to1['longitude'] = $addressdata['longitude'];
                    $to1['latitude']  = $addressdata['latitude'];
                    if ($to1['longitude'] && $to1['latitude']) {
                        $vo['realdistance'] = Geocoder::get_distance($from, $to1);
                    }
                }

                if ($vo['is_errands'] == 1) {
                    $takeaddressdata = OrderAddress::where(['order_id' => $vo['id'], 'ptype' => 2])->find();

                    if (empty($takeaddressdata)) {
                        $takeaddressdata = Address::find($vo['take_address_id']);
                    }

                    if (!empty($takeaddressdata)) {
                        $takeaddressdata  = $takeaddressdata->toArray();
                        $to2['longitude'] = $takeaddressdata['longitude'];
                        $to2['latitude']  = $takeaddressdata['latitude'];
                        if ($to2['longitude'] && $to2['latitude']) {
                            $vo['takerealdistance'] = Geocoder::get_distance($from, $to2);
                        }
                    }
                }
            }
        }

        $data['data'] = $res;

        //兼容旧版
        $data['data']["orderList"] = $res['data'];

        return $this->json($data);
    }

    public function detail()
    {
        $id   = input('get.id');
        $data = Order::order_info($id);

        if (!empty($data['orderInfo']['cat_id'])) {
            $data['orderInfo']['cateMap']['image'] = Category::getImage($data['orderInfo']['cat_id']);
        } else {
            foreach ($data['goods'] as &$vo) {
                $vo['goods']['image'] = toimg($vo['goods']['image']);
            }
        }
        if ($data['orderInfo']['additional'] > 0 && $data['orderInfo']['additional_pay_time'] == 0) {
            $tmplIds           = Config::getconfig('subscribemessage');
            $data['tmplIds'][] = $tmplIds['complete_tpl'];
        }

        $addressdata = OrderAddress::where(['order_id' => $id, 'ptype' => 1])->find();
        if (empty($addressdata)) {
            $addressdata = Address::find($data['orderInfo']['address_id']);
        }
        if (!empty($addressdata)) {
            $addressdata                  = $addressdata->toArray();
            $data['orderInfo']['address'] = $addressdata;
        }

        if ($data['orderInfo']['is_errands'] == 1) {

            $takeaddressdata = OrderAddress::where(['order_id' => $id, 'ptype' => 2])->find();

            if (empty($takeaddressdata)) {
                $takeaddressdata = Address::find($data['orderInfo']['take_address_id']);
            }

            if (!empty($takeaddressdata)) {
                $takeaddressdata = $takeaddressdata->toArray();

                $data['orderInfo']['take_address'] = $takeaddressdata;
            }
        }

        return $this->json(['data' => $data]);
    }

    public function errandscreate()
    {
        $ordermod        = new Order;
        $payment         = input('post.paymentType');
        $address_id      = input('post.address_id');
        $take_address_id = input('post.take_address_id');
        $remark          = input('post.remark');
        $distance        = input('post.distance');
        $amountTotle     = input('post.amountTotle');

        $order['distance'] = $distance;
        $order['total']    = $amountTotle;
        $order['number']   = 1;

        //支付方式
        if (!empty($payment)) {
            $order['payment_code'] = $payment;

            $paymentdata = Paymethod::where(['code' => $payment, 'weid' => weid()])->find();

            $order['pay_method_id'] = $paymentdata->id;
        }

        $order['address_id']      = $address_id;
        $order['take_address_id'] = $take_address_id;
        $order['remark']          = $remark;
        $order['uid']             = UID();

        $ordermod = new Order;
        $data     = $ordermod->add_order($order);

        return $this->json(['data' => $data]);
    }

    /**
     * @menu:创建商标订单
     * @Author:男人的坏
     * @Date:2024-03-30 16:17
     */
    public function trademark_order_create()
    {
        $orderModel                     = new TrademarkOrder();
        $trademarkModel                 = new Trademark();
        $data['trademark_id']           = input('trademark_id');
        $data['company']                = input('company');
        $data['shipping_province_name'] = input('shipping_province_name');
        $data['shipping_city_name']     = input('shipping_city_name');
        $data['shipping_district_name'] = input('shipping_district_name');
        $data['shipping_name']          = input('shipping_name');
        $data['shipping_tel']           = input('shipping_tel');
        $data['remark']                 = input('remark', '');
        $data['payment_code']           = input('paymentType');
        if (empty($data['trademark_id']) || empty($data['company']) || empty($data['shipping_province_name']) || empty($data['shipping_city_name']) || empty($data['shipping_district_name']) || empty($data['shipping_name'])) {
            return $this->json(['errno' => 10001, 'msg' => '缺少参数']);
        }
        $trademarkInfo = $trademarkModel->where(['id' => $data['trademark_id']])->findOrEmpty();
        if ($trademarkInfo->isEmpty()) {
            return $this->json(['errno' => 10001, 'msg' => '商标不存在']);
        }
        $data['uid']             = UID();
        $data['weid']            = weid();
        $data['order_num_alias'] = build_order_no();
        $data['price']           = $data['total'] = $trademarkInfo['price'];
        $orderModel->save($data);
        $data['id'] = $orderModel->id;
        return $this->json(['data' => $data]);
    }

    public function create()
    {
        $ordermod    = new Order;
        $payment     = input('post.paymentType');
        $cartid      = input('post.cartid');
        $msid        = input('post.msid');
        $tuanid      = input('post.tuanid');
        $jointuanid  = input('post.jointuanid');
        $technicalId = input('post.technicalId');
        if ($technicalId == 'undefined') {
            $technicalId = '';
        }
        $sid             = input('post.sid/d');
        $address_id      = input('post.address_id');
        $remark          = input('post.remark');
        $shipping        = input('post.shipping');
        $couponId        = input('post.couponId');
        $goods_id        = input('post.goodsId');
        $cat_id          = input('post.cat_id');
        $total           = input('post.total');
        $sku             = input('post.sku');
        $is_PayPoints    = input('post.is_PayPoints');
        $number          = input('post.number');
        $orderimage      = input('post.orderimage');
        $is_skumore      = input('post.is_skumore');
        $skumore         = json_decode(input('post.skumore'), true);
        $combination_ids = input('post.combination_ids');
        $servicetime     = input('post.servicetime');
        $is_times        = input('post.is_times');
        $servicetime     = explode(' ', $servicetime);
        $timetmp         = explode('-', $servicetime[1]);

        $order['beginTime']              = strtotime($servicetime[0].' '.$timetmp[0]);
        $order['endTime']                = strtotime($servicetime[0].' '.$timetmp[1]);
        $order['shipping_province_name'] = input('post.shipping_province_name') ?? '';
        $order['shipping_city_name']     = input('post.shipping_city_name') ?? '';
        $order['shipping_district_name'] = input('post.shipping_district_name') ?? '';
        $order['shipping_name']          = input('post.shipping_name') ?? '';
        $order['shipping_tel']           = input('post.shipping_tel') ?? '';
        $order['is_times']               = $is_times;
        $order['company']                = input('post.company') ?? '';
        $order['combination_ids']        = $combination_ids;
        $order['cartid']                 = $cartid;
        $order['sid']                    = $sid;
        $order['couponId']               = $couponId;
        $order['goods_id']               = $goods_id;
        $order['cat_id']                 = $cat_id;
        $order['total']                  = $total;
        $order['msid']                   = $msid;
        $order['tuanid']                 = $tuanid;
        $order['jointuanid']             = $jointuanid;
        $order['sku']                    = $sku;
        $order['cat_id']                 = $cat_id;
        $order['is_skumore']             = $is_skumore;
        $order['skumore']                = $skumore;
        $order['number']                 = $number;
        //需要配送的
        if (!empty($shipping)) {
            $order['shipping_method'] = '快递';
        } else {
            $order['shipping_method'] = '';
        }

        //支付方式
        if (!empty($payment)) {
            $order['payment_code'] = $payment;

            $paymentdata = Paymethod::where(['code' => $payment, 'weid' => weid()])->find();

            $order['pay_method_id'] = $paymentdata->id;
        }

        $order['address_id']  = $address_id;
        $order['technicalId'] = $technicalId;

        $order['remark']       = $remark;
        $order['is_PayPoints'] = $is_PayPoints;
        $order['uid']          = UID();
//        var_dump($order);exit();

        $data = $ordermod->add_order($order);
        //图片
        if ($data['id']) {
            OrderImage::where('order_id', $data['id'])->delete();
            if (!empty($orderimage)) {
                foreach (explode(',', $orderimage) as $image) {
                    OrderImage::create([
                        'order_id' => (int)$data['id'],
                        'weid'     => weid(),
                        'image'    => $image
                    ]);
                }
            }

            if (!empty($technicalId)) {
                $order_staff['order_id']    = $data['id'];
                $order_staff['uuid']        = $technicalId;
                $order_staff['create_time'] = time();
                OrderStaff::addstaff($order_staff);
                Message::sendMiniStaff($order);
                Message::distribution($technicalId, $data);
            }
        }

        return $this->json(['data' => $data]);
    }

    public function yuyuetime()
    {
        $id          = input('post.id');
        $timestype   = input('post.timestype');
        $timesdate   = input('post.timesdate');
        $servicetime = input('post.servicetime');

        $servicetime = explode(' ', $servicetime);
        $timetmp     = explode('-', $servicetime[1]);

        $order['beginTime'] = strtotime($servicetime[0].' '.$timetmp[0]);
        $order['endTime']   = strtotime($servicetime[0].' '.$timetmp[1]);

        $order['timestype'] = $timestype;
        $order['timesdate'] = $timesdate;
        $order['id']        = $id;

        Order::update($order);
        return $this->json(['data' => []]);
    }

    public function close()
    {
        $this->cancel();
    }

    public function cancel()
    {
        $orderid = input('post.orderid');

        Order::cancel_order($orderid);

        $data['orderid'] = $orderid;

        return $this->json(['data' => $data]);
    }

    public function receiving()
    {
        $orderid = input('post.orderid');

        Order::receiving($orderid);

        $data['orderid'] = $orderid;

        return $this->json(['data' => $data]);
    }

    public function additional()
    {
        $orderid    = input('post.orderid');
        $additional = input('post.additional');

        $order['additional'] = $additional;
        Order::where('id', $orderid)->update($order);

        $order_info = Order::find($orderid);
        if (!empty($order_info)) {
            $order_info = $order_info->toArray();
        }
        Message::sendMiniItional($order_info);
        return $this->json(['data' => []]);
    }


    public function complete()
    {
        $orderid = input('post.orderid');
        try {
            $data = Order::complete($orderid);
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }

        return $this->json(['data' => $data]);
    }

    function staff()
    {
        $id   = input('post.id');
        $uuid = input('post.uuid');
        $msg  = '派单';
        if (empty($uuid)) {
            $uuid = $this->getuuid();
            $msg  = '接单';
        }

        $orderInfo = Order::find($id);

        if (!empty($orderInfo)) {
            $orderInfo = $orderInfo->toArray();

            if ($orderInfo['order_status_id'] == 2) {
                $order_history['order_status_id'] = 3;
                $orderup['order_status_id']       = 3;
                $uuid                             = $this->getuuid();
                $Storedata                        = Store::where(['uuid' => $uuid])->find();
                $orderup['sid']                   = $Storedata['id'];
            }

            try {

                $order_history['order_id']    = $orderInfo['id'];
                $order_history['remark']      = $msg;
                $order_history['create_time'] = time();
                $order_history['notify']      = 1;

                OrderHistory::create($order_history);

                if ($uuid) {
                    $order_staff['order_id']    = $orderInfo['id'];
                    $order_staff['uuid']        = $uuid;
                    $order_staff['create_time'] = time();
                    OrderStaff::addstaff($order_staff);
                    Message::sendMiniStaff($orderInfo);
                }
                $orderup['id'] = $orderInfo['id'];
                order::update($orderup);
            } catch (\Exception $e) {
                throw new ValidateException($e->getMessage());
            }
        }

        return $this->json(['msg' => $msg.'成功']);
    }

    //付款凭证上传
    public function offlinepayment()
    {
        $orderid = input('post.orderid');
        $img     = input('post.image');
        $remark  = input('post.remark');

        $order  = new Order;
        $insert = $order->OfflinepaymentTap($orderid, $img, $remark);

        if ($insert) {
            Order::offline_order($orderid);

            $errno   = 0;
            $message = '提交成功，请等待管理员审核！';

            return $this->json(['message' => $message, 'data' => []]);
        } else {
            $errno   = 1;
            $message = '提交失败，请重新尝试!';
            return $this->json(['message' => $message, 'data' => []]);
        }
    }

    public function custom()
    {
        $id            = input('post.id');
        $registerfield = json_decode(input('post.registerfield'), true);

        $data = RegisterField::fieldToData($registerfield);

        Order::where('id', $id)->update(['customtext' => $data['customtext']]);

        $msg = '提交成功';
        return $this->json(['msg' => $msg, 'data' => $data]);
    }

    public function taketotal()
    {
        $address_id      = input('post.address_id');
        $take_address_id = input('post.take_address_id');

        $addressdata = Address::find($address_id);
        if (!empty($addressdata)) {
            $addressdata = $addressdata->toArray();
        }
        $takeaddressdata = Address::find($take_address_id);
        if (!empty($takeaddressdata)) {
            $takeaddressdata = $takeaddressdata->toArray();
        }

        if ($addressdata['longitude'] && $addressdata['latitude'] && $takeaddressdata['longitude'] && $takeaddressdata['latitude']) {
            $from['longitude'] = $addressdata['longitude'];
            $from['latitude']  = $addressdata['latitude'];
            $to['longitude']   = $takeaddressdata['longitude'];
            $to['latitude']    = $takeaddressdata['latitude'];

            $data["distance"] = Geocoder::get_distance($from, $to);
        }

        if ($data["distance"]) {
            $errands = Config::getconfig('errands');

            $data["amountTotle"] = round(($data["distance"] * $errands['mileageprice']), 2);
        }

        return $this->json(['data' => $data]);
    }

    public function total()
    {
        $charge      = 0;
        $cartid      = input('post.cartid');
        $msid        = input('post.msid');
        $tuanid      = input('post.tuanid');
        $ptype       = input('post.ptype');
        $address_id  = input('post.address_id');
        $peisongType = input('post.peisongType');
        $technicalId = input('post.technicalId');
        if ($technicalId == 'undefined') {
            $technicalId = '';
        }

        if (empty($cartid)) {
            $goods_id                 = input('post.goodsId');
            $sku                      = input('post.sku');
            $number                   = input('post.number');
            $is_skumore               = input('post.is_skumore');
            $skumore                  = json_decode(input('post.skumore'), true);
            $Goods                    = new Goods;
            $buygoods                 = $Goods->cartGoods([
                'id'         => $goods_id,
                'msid'       => $msid,
                'tuanid'     => $tuanid,
                'sku'        => $sku,
                'quantity'   => $number,
                'is_skumore' => $is_skumore,
                'skumore'    => $skumore
            ]);
            $data["amountTotle"]      = $buygoods['total'];
            $data["totalPayPoints"]   = $buygoods['totalPayPoints'];
            $data['totalPointsPrice'] = $buygoods['totalPointsPrice'];
            $data['is_additional']    = $buygoods['is_additional'];

            if (empty($buygoods['weight'])) {
                $buygoods['weight'] = 0.1;
            }
            $weight = $buygoods['weight'];
            //var_dump($weight);
        } else {
            $cart                     = new Cart;
            $cartgoods                = $cart->getlistbyid($cartid);
            $data["amountTotle"]      = $cartgoods['totalprice'];
            $data["totalPayPoints"]   = $cartgoods['totalPayPoints'];
            $data['totalPointsPrice'] = $cartgoods['totalPointsPrice'];
            $data['is_additional']    = $cartgoods['is_additional'];
            $weight                   = $cartgoods['weight'];
        }

        $data["thefare"] = 0;

        //收货人
        if (!empty($address_id)) {
            $shipping = Address::find($address_id);
            if (!empty($shipping)) {
                $shipping = $shipping->toArray();
            }
            if ($ptype == 1) {

                $shipping_city_id = empty($shipping['city_id']) ? '' : $shipping['city_id'];

                $Transport       = (new TransportExtend)->calc_transport($weight, $shipping_city_id);
                $amountLogistics = $Transport['price'];
            }

            if ($technicalId && $ptype == 2) {
                $thefare          = Address::getthefare($address_id, $technicalId);
                $data["distance"] = $thefare['distance'];
                $data["thefare"]  = $thefare['thefare'];
            }
        }

        $Membermob = new Member;
        $Member    = $Membermob->getUserByWechat();

        //订阅消息模板
        $tmplIds           = Config::getconfig('subscribemessage');
        $data['tmplIds'][] = $tmplIds['pay_tpl'];
        $data['tmplIds'][] = $tmplIds['staff_tpl'];
        if ($data['is_additional'] == 1) {
            $data['tmplIds'][] = $tmplIds['itional_tpl'];
        } else {
            $data['tmplIds'][] = $tmplIds['complete_tpl'];
        }

        $data["memberPoints"]     = $Member['points'];
        $test['shipping_method']  = '快递';
        $test['weight']           = $weight;
        $test['shipping_city_id'] = $shipping_city_id;
        $data["amountLogistics"]  = (float)$amountLogistics;
        $data['charge']           = $charge;
        $data["isNeedLogistics"]  = 1;
        $data["peisongType"]      = $peisongType;
        $data['test']             = $test;
        $data["amountTotle"]      = round($data["amountTotle"], 2);


        return $this->json(['data' => $data]);
    }

    //直接使用余额支付
    public function pay()
    {

        $orderid = input('post.orderid');

        //付款前检查库存
        $result = Order::getGoodsquantitiy($orderid);

        if ($result) {
            $orderinfo = Order::find($orderid);

            if (!empty($orderinfo)) {
                $orderinfo = $orderinfo->toArray();
                $money     = $orderinfo['total'];
                $Member    = Member::find(UID());
                if (!empty($Member) && ($Member->balance >= $money)) {
                    Member::where('id', UID())
                        ->dec('balance', $money)
                        ->update();

                    Order::update(['id' => $orderid, 'pay_time' => time(), 'payment_code' => 'balance']);

                    $ordermod = new Order;
                    $ordermod->pay_order(['id' => $orderid]);
                } else {
                    $errno   = 1;
                    $message = '余额不足';
                }
            } else {
                $errno   = 1;
                $message = '订单不存在';
            }
        } else {
            $errno   = 2;
            $message = '库存量不足';
        }

        return $this->json(['msg' => $message, 'message' => $message, 'errno' => $errno, 'data' => []]);
    }

    //直接使用余额支付
    public function trademark_pay()
    {

        $orderid        = input('post.orderid');
        $orderModel     = new TrademarkOrder();
        $trademarkModel = new Trademark();
        //付款前检查库存
        $result = $orderModel->where(['id' => $orderid, 'order_status_id' => 1])->findOrEmpty();
        if ($result->isEmpty()) {
            return $this->json(['errno' => 10001, 'msg' => '订单不存在']);
        }
        $orderinfo = $result->toArray();
        $money     = $orderinfo['total'];
        $Member    = Member::find(UID());
        if (!empty($Member) && ($Member->balance >= $money)) {
            $Member->dec('balance', $money)->inc('totleconsumed', $money)->update();
            $result->pay_time        = time();
            $result->payment_code    = 'balance';
            $result->order_status_id = 5;
            $result->pay_money = $money;
            $result->save();
            $orderModel->pay_order($result);
            $trademarkModel->where(['id' => $result->trademark_id])->inc('sale_count', 1)->update();
        } else {
            $errno   = 1;
            $message = '余额不足';
        }
        return $this->json(['msg' => $message, 'message' => $message, 'errno' => $errno, 'data' => []]);
    }

    /**
     * @menu:取消订单
     * @Author:男人的坏
     * @Date:2024-04-01 12:14
     */

    public function trademark_del()
    {
        $orderid    = input('orderid');
        $orderModel = new TrademarkOrder();
        if (!$orderid) {
            return $this->json(['errno' => 10001, 'msg' => '缺少参数']);
        }
        $result = $orderModel->where(['id' => $orderid, 'order_status_id' => 1, 'uid' => UID()])->findOrEmpty();
        if ($result->isEmpty()) {
            return $this->json(['errno' => 10001, 'msg' => '订单不存在']);
        }
        $result->delete();
        return $this->json(['msg' => '操作成功']);
    }

    /**
     * @menu:用户订单列表
     * @Author:男人的坏
     * @Date:2024-04-01 13:45
     */

    public function trademark_order_list()
    {
        $orderModel      = new TrademarkOrder();
        $order_status_id = input('order_status_id');
        $where['uid']    = UID();
        if (isset($order_status_id) && $order_status_id != '') {
            $where['order_status_id'] = $order_status_id;
        }
        $data = $orderModel->with([
            'trademark' => function ($query) {
                $query->field('id,name,image');
            }
        ])->where($where)->order('id desc')->paginate();
        return $this->json(['data' => $data]);
    }

    public function service_order_list(){
        $weid = weid();
        $where['weid'] = $weid;
//        $where['uid'] =  UID();
        $where['ptype'] = 2;
        $where['is_times'] = 0;
        $query = Order::where($where);
        $create_time = input('time','');
        if (!$create_time) {
            $str_time = strtotime(date('Y-m-d',strtotime('-30 day', time())));
            $end_time = time();
            $query = $query->whereBetween('create_time', [$str_time,$end_time]);
        }
        if (!empty($keyword)) {
            $query->where('name|pay_subject|shipping_tel|order_num_alias', 'like', '%' . $keyword . '%');
        }
        $city_name = input('city_name');
        if($city_name){
            $query->where('shipping_city_name_two', '=', $city_name);
        }
        $res = $query->with(['member', 'orderGoods', 'paymethod'])->order('id desc')
            ->paginate(getpage())
            ->toArray();
        foreach ($res['data'] as &$vo) {

            $vo['sid'] = Store::getTitle($vo['sid']);
            $vo['staff'] = OrderStaff::staff($vo['id']);
            $vo['create_time'] = time_format($vo['create_time']);
            $vo['pay_time'] = time_format($vo['pay_time']);

            if (empty($vo['orderGoods'])) {
                if (!empty($vo['cat_id'])) {
                    $vo['orderGoods'][0]['image'] = Category::getImage($vo['cat_id']);
                }
                $vo['orderGoods'][0]['name'] = '【用户发布需求】' . $vo['pay_subject'];
            }
            if ($vo['ptype'] == 1) {
                $vo['order_status'] = OrderStatus::get_order_status_name($vo['order_status_id']);
            } else {
                $vo['order_status'] = OrderStatus::get_order_status_name_yuyue($vo['order_status_id']);
            }

            if($vo['payment_code'] == "balance"){
                $vo['payment_code_name'] = 	'余额支付';
            }else{
                $vo['payment_code_name'] = 	Paymethod::get_paymethod_name($vo['payment_code']);
            }

            $vo['shipping_type'] = getdeliverymode($vo['deliverymode']);

            if ($vo['is_times'] == 1) {

                if ($vo['timesdate']) {
                    if ($vo['timestype'] == 1) {
                        $vo['yue_time'] = '每月:' . $vo['timesdate'] . '号';
                    } else {
                        $vo['yue_time'] = '每周周:' . $vo['timesdate'];
                    }
                } else {
                    $vo['yue_time'] = '还没有预约时间';
                }
            } else {
                $vo['yue_time'] = time_format($vo['beginTime']) . ' 到 ' . date('H:i', $vo['endTime']);
            }

            $vo['fwaddress'] = $vo['shipping_district_name_two'].$vo['shipping_city_name_two'];
            if (!empty($vo['orderGoods'])) {

                foreach ($vo['orderGoods'] as &$vvo) {
                    $vvo['image'] = toimg($vvo['image']);
                }
            }
        }

        return $this->json($res);
    }

    /**
     * @menu:平台订单列表
     * @Author:男人的坏
     * @Date:2024-04-01 15:37
     */
    public function trademark_order_listall()
    {
        $orderModel               = new TrademarkOrder();
        $where['order_status_id'] = 5;
        $str_time = strtotime(date('Y-m-d',strtotime('-30 day', time())));
        $end_time = time();
        $time  = input('time','');
        $query =  $orderModel->with([
            'trademark' => function ($query) {
                $query->field('id,name,image');
            }
            ,'member'=>function($query){
                $query->field('id,nickname,userpic');
            }])->where($where);
        if($time){
            $query = $query->whereBetween('create_time', [$str_time,$end_time]);
        }
        $data   =$query->order('id desc')->field('id,uid,trademark_id,order_num_alias,pay_time,create_time')->order('id desc')->paginate();
        return $this->json(['data' => $data]);
    }

    /**
     * @menu 订单详情
     * @Author:男人的坏
     * @Date:2024-04-01 13:55
     */
    public function trademark_order_info()
    {
        $orderModel   = new TrademarkOrder();
        $ids          = input('ids');
        $where['uid'] = UID();
        $where['id']  = $ids;
        $info         = $orderModel->with([
            'trademark' => function ($query) {
                $query->field('id,name,image');
            }
        ])->where($where)->find();
        return $this->json(['info' => $info]);
    }

    public function delivery()
    {

        $orderid = input('post.orderid');

        $orderinfo = Order::find($orderid);
        if (!empty($orderinfo)) {
            if ($orderinfo['order_status_id'] === 5) {
                Order::where('id', $orderid)->update([
                    'is_check' => 1
                ]);
            } else {
                $orderinfo                        = $orderinfo->toArray();
                $order_history['order_id']        = $orderid;
                $order_history['order_status_id'] = 5;
                $order_history['remark']          = "已收货";
                $order_history['create_time']     = time();
                $order_history['notify']          = 1;
                OrderHistory::create($order_history);

                $order['order_status_id'] = 5;
                Order::where('id', $orderid)->update($order);
            }
        } else {
            $errno   = 1;
            $message = '订单不存在';
        }
        return $this->json(['message' => $message, 'errno' => $errno, 'data' => []]);
    }

    //支付方式列表
    public function paymethod()
    {

        $data               = Paymethod::where(['weid' => weid(), 'status' => 1])
            ->order('sort asc')
            ->select()
            ->toArray();
        $data[0]['default'] = $data[0]['default']['code'];
        foreach ($data as $i => $vo) {
            if (empty($vo['code'])) {
                unset($data[$i]);
            }
            if (($vo['code'] == 'wx_pay')) {
                $data[0]['default'] = $vo['code'];
            }
        }
        if (empty($data)) {
            Paymethod::update(['code' => 'wx_pay', 'weid' => 0]);
            $data = Paymethod::where(['weid' => 0])->order('sort asc')->select()->toArray();
        }
        if (empty($data[0]['default'])) {
            $data[0]['default'] = $data[0]['code'];
        }
        return $this->json(['data' => $data]);
    }


    /**
     * 提交资料
     */

    public function submit_profile()
    {
        $ids            = input('post.ids');
        $profile_string = input('post.profile_string');
        if (!$ids || !$profile_string) {
            return $this->json(['message' => '缺少参数', 'errno' => 10010, 'data' => []]);
        }
        $Membermob = new Member;
        $Member    = $Membermob->getUserByWechat();
        $weid      = weid();
        $orderInfo = Order::where(['id' => $ids, 'weid' => $weid, 'uid' => $Member['id']])->find();
        if (!$orderInfo) {
            return $this->json(['message' => '订单不存在', 'errno' => 10011]);
        }
        if ($orderInfo->order_status_id != 3) {
            return $this->json(['message' => '订单状态已被修改', 'errno' => 10012]);
        }
        $orderInfo->profile_string  = $profile_string;
        $orderInfo->order_status_id = 8;
        $orderInfo->save();
        return $this->json(['message' => '操作成功']);
    }

    /**
     * 驳回
     */

    public function reject_profile()
    {
        $ids = input('post.ids');
        if (!$ids) {
            return $this->json(['message' => '缺少参数', 'errno' => 10010, 'data' => []]);
        }
        $weid      = weid();
        $uuid      = $this->getuuid();
        $Storedata = Store::where(['uuid' => $uuid])->find();
        $orderInfo = Order::where(['id' => $ids, 'weid' => $weid, 'sid' => $Storedata['id']])->find();
        if (!$orderInfo) {
            return $this->json(['message' => '订单不存在', 'errno' => 10010, 'data' => []]);
        }
        if ($orderInfo->order_status_id != 8) {
            return $this->json(['message' => '订单状态已被更改', 'errno' => 10010, 'data' => []]);
        }
        $orderInfo->order_status_id = 3;
        $orderInfo->profile_string  = '';
        $orderInfo->save();
        return $this->json(['message' => '操作成功']);
    }

}
